package web

import (
	"ginstudy/app/global/consts"
	"ginstudy/app/global/variable"
	"ginstudy/app/model"
	"ginstudy/app/service/users/curd"
	userstoken "ginstudy/app/service/users/token"
	"ginstudy/app/utils/response"
	"time"

	"github.com/gin-gonic/gin"
)

type Users struct {
}

// 1. 用户登录
func (u *Users) Login(context *gin.Context) {
	userName := context.GetString(consts.ValidatorPrefix + "user_name")
	pass := context.GetString(consts.ValidatorPrefix + "pass")
	userModelFact := model.CreateUserFactory("")
	userModel := userModelFact.Login(userName, pass)

	if userModel != nil {
		userTokenFactory := userstoken.CreateUserFactory()
		if userToken, err := userTokenFactory.GenerateToken(userModel.Id, userModel.UserName, userModel.Phone, variable.ConfigYml.GetInt64("Token.JwtTokenCreatedExpireAt")); err == nil {
			if userTokenFactory.RecordLoginToken(userToken, context.ClientIP()) {
				data := gin.H{
					"userId":     userModel.Id,
					"user_name":  userName,
					"realName":   userModel.RealName,
					"phone":      userModel.Phone,
					"token":      userToken,
					"updated_at": time.Now().Format(variable.DateFormat),
				}
				response.Success(context, consts.CurdStatusOkMsg, data)
			}
		}
	}
}

// 2.用户注册
func (u *Users) Register(context *gin.Context) {
	// 由于本项目骨架已将表单验证器的字段（成员）绑定在上下文，因此可以按照GetString(), GetInt64(), GetFloat64() 等快捷获取需要的数据类型，注意：相关键名规则：..前缀 + 验证器结构体中的 json标签
	// 当然也可以通过gin框架的上下文原始方法获取，例如：context.PostForm("user_name")获取，这样获取的数据格式为文本，需要自己继续转换
	userName := context.GetString(consts.ValidatorPrefix + "user_name")
	pass := context.GetString(consts.ValidatorPrefix + "pass")
	userIp := context.ClientIP()
	if curd.CreateUserCurdFactory().Register(userName, pass, userIp) {
		response.Success(context, consts.CurdStatusOkMsg, "")
	} else {
		response.Fail(context, consts.CurdRegisterFailCode, consts.CurdRegisterFailMsg, "")
	}
}
